import { createRouter, createWebHistory } from "vue-router";
// import pinia from '@/pinia'
import { useUserStore } from "@/pinia/userStore";
import subscribe from "@/utils/subscribe";
import { getUserInfoBySessionApi } from '@/api/user.js'


let routes = [
{
  path: "/",
  component: () => import("@/views/Home/Index.vue"),
  meta: {
    
    },
  redirect:"/all",
  children: [
    {
      path: ":id?",
      component: () => import("@/views/Information/Index.vue"),
      meta: {
      }
    },
    {
      path: "infos",
      component: () => import("@/views/Infos/Index.vue"),
      meta: {
        
      },
      children: [
        {
          path: "newBuddyList",
          component:()=>import("@/views/Infos/NewBuddyList/Index.vue")
        },
        {
          path: "buddyInfo/:id",
          component:()=>import("@/views/Infos/BuddyInfo/Index.vue")
        },
      ]
    }
  ]
  },
  {
  path: "/login",
  beforeEnter: async (to, from, next) => {
    try {
      const userStore = useUserStore();
      if (!userStore.loginStatus) {
        const user = await getUserInfoBySessionApi()
        userStore.setLoginInfo(user);
        init(user)
        next(to.query.redirect??'/');
      }
    } catch (e) {
      next();
    }
  },
  component: () => import("@/views/Login/Index.vue"),
  
}];



 



function init (user) {
  import("@/websocket/clientRunner.js")
  subscribe.on("WEBSOCKET:CONNECTION", () => {
    subscribe.emits("WEBSOCKET:SEND", { type: "CONNECT", message: "连接请求", userId: user.id })
  })
}



const router = createRouter({
  routes,
  history: createWebHistory(),
  linkActiveClass: "active",
  linkExactActiveClass: "active"
});

subscribe.on("ROUTER:SKIT", (e) => {
    router.push(e)
})



router.beforeEach(async (to, from, next) => {
  if (to.path === '/login') {
    return next()
  }
  const userStore = useUserStore();
  // 判断用户是否登录
  if (!userStore.loginStatus) {
    //发送请求
    let path = joinPath(to);
    // 拼接
    next(path)
    return;
  }
  next()
})

// 拼接跳转路径
function joinPath (to) {
  let redirect = (to.fullPath)??'/'
  return "/login?redirect="+redirect
}

export default router;